<template>
  <SuperTable :data-request="fetchData" :columns="columns" header-title="样本类型管理" pager align="center" border search ref="superTableRef" :export-config="{}">
    <template #action>
      <Button type="primary" @click="showEditDrawerFn(null)">新建模板</Button>
    </template>
  </SuperTable>

  <Drawer v-model:visible="state.showEditDrawer" width="900" :closable="false">
    <!--   标题   -->
    <template #title>
      <HeaderTitle :title="`${state.currentTitle}样本模板`" />
    </template>
    <!--   右上按钮   -->
    <template #extra>
      <CloseOutlined @click="editDrawerCancelFn" />
    </template>
    <!--   底部按钮   -->
    <template #footer>
      <Space style="display: flex; justify-content: center" size="large">
        <Button @click="editDrawerCancelFn">取消</Button>
        <Button type="primary" @click="editDrawerOkFn">保存</Button>
      </Space>
    </template>
    <!--   主体内容   -->
    <Form :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
      <Row>
        <Col :span="12">
          <FormItem label="模板名称" :required="true">
            <Input v-model:value="state.templateName" />
          </FormItem>
        </Col>
      </Row>
      <Row v-if="state.typeList?.length">
        <Col :span="12" v-for="(item, index) in state.typeList" :key="index">
          <FormItem :label="item.name" :required="item.fieldRequired === 1">
            <div class="boxItem">
              <Select allowClear :options="item.valueRange.split('|').map((item) => ({ label: item, value: item }))" :placeholder="item.memo" />
              <CloseCircleTwoTone v-show="state.typeList?.length > 1" class="delBtn" twoToneColor="#f9b1b9" @click="delTypeFn(index)" />
            </div>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="12" v-for="(item, index) in state.fieldList" :key="index">
          <FormItem :label="item.name" :required="item.fieldRequired === 1">
            <div class="boxItem">
              <Select allowClear v-if="item.valueType === 4" :options="item.valueRange.split('|').map((item) => ({ label: item, value: item }))" :placeholder="item.memo" />
              <Input v-else :placeholder="item.memo" />
              <CloseCircleTwoTone v-if="item.editType !== 1" class="delBtn" twoToneColor="#f9b1b9" @click="delFieldFn(index)" />
            </div>
          </FormItem>
        </Col>
      </Row>
      <Button style="margin-left: 106px" type="white-blue" @click="state.showFieldModal = true">新增字段</Button>
    </Form>
    <!--   字段弹窗   -->
    <EditModal v-model:show-modal="state.showFieldModal" :title="state.currentTitle" :data="null" :type="1" @edit-modal-ok="addFieldFn" />
  </Drawer>
</template>

<script setup lang="tsx">
import EditModal from '@/modules/sample_manage/pages/field-management/components/edit-modal.vue';
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import Button from '@/framework/components/basic/button/button.vue';
import HeaderTitle from '@/components/headerTitle.vue';
import { message, Drawer, Form, FormItem, Select, Row, Col, Space, Input } from 'ant-design-vue';
import { CloseOutlined, CloseCircleTwoTone } from '@ant-design/icons-vue';
import { baseColumns, TableColumnItem } from './columns';
import { VxeGridPropTypes } from 'vxe-table';
import { reactive, ref } from 'vue';
import { addSampleTemplate, delSampleType, getSampleTemplate, getSampleType, updateSampleTemplate } from '@/modules/sample_manage/api/template-management';
import { getcustomerFormData } from '@/api/public';

/**
 * data
 */
const state: {
  showEditDrawer: boolean;
  showFieldModal: boolean;

  currentTitle: '新建' | '编辑' | '复制';
  templateName: string;

  currentID: any;
  fieldList: any[];
  typeList: any[];
  systemList: any[];
} = reactive({
  showEditDrawer: false,
  showFieldModal: false,

  currentTitle: '新建',
  templateName: '',

  currentID: '',
  fieldList: [],
  typeList: [],
  systemList: [],
});

/**
 * table
 */
const superTableRef = ref<InstanceType<typeof SuperTable>>();
let columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    field: '$action',
    width: 230,
    actions: ({ row }) => [
      {
        label: '编辑',
        onClick: async () => {
          state.currentTitle = '编辑';
          state.templateName = row?.name;
          state.currentID = row?.id;
          await showEditDrawerFn(row?.commonCfgEntityList);
        },
      },
      {
        label: '复制',
        onClick: async () => {
          state.currentTitle = '复制';
          await showEditDrawerFn(row?.commonCfgEntityList);
        },
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除该模板？',
          onConfirm: async () => {
            await delSampleType(row.id);
            message.success('删除成功！');
            superTableRef.value?.refreshTable();
          },
        },
      },
    ],
  },
];
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let searchData = superTableRef.value?.getFormModel();
  let params = {
    ...searchData,
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    'orderBy[0].field': 'createTime', // 默认排序字段
    'orderBy[0].order': 'desc', // 默认排序方式
  };
  const { result } = await getSampleTemplate(params);
  return result;
};

/**
 * drawer
 */
const showEditDrawerFn = async (list) => {
  switch (state.currentTitle) {
    case '复制':
    case '编辑':
      state.fieldList = list.filter((item) => {
        return !item.value;
      });
      break;
    case '新建':
      const { result: systemList } = await getcustomerFormData();
      state.fieldList = systemList.filter((item) => item.editType === 1);
      break;
  }
  const { result } = await getSampleType();
  state.typeList = result?.map((item, index) => ({
    fieldRequired: 1,
    key: item.specimenTypeFormwork + '_' + item.id,
    memo: '',
    name: item.classify,
    sortIndex: 0,
    valueType: 4,
    valueRange: item.value,
    editType: 2,
    value: item.id,
  }));

  state.showEditDrawer = true;
};
const editDrawerCancelFn = () => {
  state.showEditDrawer = false;
  state.currentTitle = '新建';
  state.fieldList = [];
  state.typeList = [];
  state.templateName = '';
  state.currentID = '';
};
const editDrawerOkFn = async () => {
  if (!state.templateName) {
    return message.warn('模板名称为必填项！');
  }
  let params = {
    name: state.templateName,
    commonCfgEntityList: [...state.typeList, ...state.fieldList],
  };
  switch (state.currentTitle) {
    case '复制':
    case '新建':
      params.commonCfgEntityList.forEach((item) => {
        delete item.id;
      });
      await addSampleTemplate(params);
      break;
    case '编辑':
      await updateSampleTemplate(state.currentID, params);
      break;
  }
  message.success('操作成功！');
  superTableRef.value?.refreshTable();
  editDrawerCancelFn();
};
/**
 * field
 */
const addFieldFn = (params: any) => {
  state.fieldList.push(params);
  state.fieldList.sort((a, b) => {
    return a.sortIndex - b.sortIndex;
  });
};
const delFieldFn = (index: number) => {
  state.fieldList.splice(index, 1);
};
const delTypeFn = (index: number) => {
  state.typeList.splice(index, 1);
};
</script>

<style scoped lang="less">
.boxItem {
  position: relative;

  .delBtn {
    position: absolute;
    top: -6px;
    right: -6px;
    display: none;
  }

  &:hover {
    .delBtn {
      display: block;
    }
  }
}
</style>
